from typing import List, Optional, Any
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from sqlalchemy.sql import func  # Add this for random() function

from app.api import deps
from app.crud import crud_question
from app.models.question import Question
from app.schemas.question import (
    QuestionCreate,
    QuestionResponse,
    ExamRequest,
    QuestionAnswer,
    QuestionResult
)
from app.crud.crud_question import (
    get_questions_by_subject_and_model,
    get_question_by_id,
    get_random_questions,
    get_questions,
    get_question,
    create_question
)
from app.db.database import get_db

router = APIRouter()

@router.post("/", response_model=QuestionResponse)
def create_new_question(
    question: QuestionCreate,
    db: Session = Depends(deps.get_db)
):
    return create_question(db=db, question=question)

@router.get("/", response_model=List[QuestionResponse])
def read_questions(
    skip: int = 0,
    limit: int = 100,
    db: Session = Depends(deps.get_db)
):
    questions = get_questions(db, skip=skip, limit=limit)
    return questions

@router.get("/{question_id}", response_model=QuestionResponse)
def read_question(question_id: int, db: Session = Depends(deps.get_db)):
    db_question = get_question(db, question_id=question_id)
    if db_question is None:
        raise HTTPException(status_code=404, detail="Question not found")
    return db_question

@router.get("/exam/{subject}/{vehicleType}", response_model=List[QuestionResponse])
async def get_exam_questions(
    subject: str,
    vehicleType: str,
    examType: str = "theory",
    questionCount: int = 100,
    db: Session = Depends(get_db)
):
    """
    获取考试题目
    - subject: 科目类型 (k1, k4)
    - vehicleType: 车型 (C1, C2, etc.)
    - examType: 考试类型 (theory, practice)
    - questionCount: 题目数量
    """
    questions = get_random_questions(
        db=db,
        subject=subject,
        model=vehicleType,
        limit=questionCount
    )
    return questions

@router.post("/{question_id}/check", response_model=QuestionResult)
def check_answer(
    question_id: int,
    answer: QuestionAnswer,
    db: Session = Depends(deps.get_db)
):
    question = get_question(db, question_id=question_id)
    if not question:
        raise HTTPException(status_code=404, detail="Question not found")
    
    is_correct = question.answer == answer.user_answer
    return QuestionResult(
        question_id=question_id,
        is_correct=is_correct,
        correct_answer=question.answer,
        explanation=question.explanation
    )

@router.post("/theory-exam", response_model=List[QuestionResponse])
def get_theory_exam(
    request: ExamRequest,
    db: Session = Depends(deps.get_db)
):
    """
    获取理论考试题目
    - subject: 考试科目 (k1: 科目一, k4: 科目四)
    - vehicleType: 车辆类型 (C1: 轿车, A2: 货车, D: 摩托车, A1: 公交车)
    - questionCount: 题目数量 (默认100题)
    """
    query = db.query(Question).filter(
        Question.subject == request.subject,
        Question.model == request.vehicleType,
        Question.question_type == 'theory'
    )
    
    # 随机获取指定数量的题目
    questions = query.order_by(func.random()).limit(request.questionCount).all()
    
    if not questions:
        raise HTTPException(status_code=404, detail="未找到符合条件的题目")
    
    return questions

@router.post("/special-training", response_model=List[QuestionResponse])
def get_special_training(
    request: ExamRequest,
    db: Session = Depends(deps.get_db)
):
    """
    获取专项训练题目
    - subject: 考试科目 (k1: 科目一, k4: 科目四)
    - vehicleType: 车辆类型 (C1: 轿车, A2: 货车, D: 摩托车, A1: 公交车)
    """
    query = db.query(Question).filter(
        Question.subject == request.subject,
        Question.model == request.vehicleType,
        Question.question_type == 'special'
    )
    
    questions = query.all()
    
    if not questions:
        raise HTTPException(status_code=404, detail="未找到符合条件的题目")
    
    return questions

@router.get("/sequence/{subject}", response_model=List[QuestionResponse])
async def get_sequence_questions(
    subject: str,
    mode: str = "sequence",
    db: Session = Depends(get_db)
):
    """
    获取顺序练习题目
    - subject: 科目类型 (k1, k4)
    - mode: 练习模式 (sequence)
    """
    questions = get_questions_by_subject_and_model(
        db=db,
        subject=subject,
        model="C1",  # 默认使用 C1 车型
        limit=100
    )
    return questions

@router.get("/practice/{subject}/{vehicleType}", response_model=List[QuestionResponse])
async def get_practice_questions(
    subject: str,
    vehicleType: str,
    skip: int = 0,
    limit: int = 100,
    db: Session = Depends(get_db)
):
    """
    获取练习题目
    - subject: 科目类型 (k1, k4)
    - vehicleType: 车型 (C1, C2, etc.)
    """
    questions = get_questions_by_subject_and_model(
        db=db,
        subject=subject,
        model=vehicleType,
        skip=skip,
        limit=limit
    )
    return questions

@router.get("/random/{subject}/{model}", response_model=List[QuestionResponse])
def get_random_practice_questions(
    subject: str,
    model: str,
    count: int = Query(100, gt=0),
    db: Session = Depends(deps.get_db)
):
    """获取随机练习题目"""
    questions = get_random_questions(
        db, subject=subject, model=model, limit=count
    )
    return questions

@router.get("/{question_id}", response_model=QuestionResponse)
def get_question_detail(
    question_id: int,
    db: Session = Depends(deps.get_db)
):
    """获取题目详情"""
    question = get_question_by_id(db, question_id)
    if not question:
        raise HTTPException(status_code=404, detail="Question not found")
    return question

# Optional: Add update and delete endpoints if needed
# @router.put("/{question_id}", response_model=schemas.Question)
# def update_question(
#     *, 
#     db: Session = Depends(deps.get_db), 
#     question_id: int, 
#     question_in: schemas.QuestionUpdate
# ) -> Any:
#     """更新题目"""
#     question = crud.crud_question.get_question(db=db, question_id=question_id)
#     if not question:
#         raise HTTPException(status_code=404, detail="Question not found")
#     question = crud.crud_question.update_question(db=db, question_id=question_id, question_update=question_in)
#     return question
#
# @router.delete("/{question_id}", response_model=schemas.Question) 
# def delete_question(
#     *, 
#     db: Session = Depends(deps.get_db), 
#     question_id: int,
# ) -> Any:
#     """删除题目"""
#     question = crud.crud_question.get_question(db=db, question_id=question_id)
#     if not question:
#         raise HTTPException(status_code=404, detail="Question not found")
#     question = crud.crud_question.delete_question(db=db, question_id=question_id)
#     return question 